from mtp.lib.plugin import Plugin 
from mtp.lib.pageaction import PageAction
from mtp.lib.base import *
import difflib


class HistoryController(BaseController):
    def index(self, page_id, format='html'):
        c.page = model.Page.getByTitle(page_id)
        return render('/history/list.%s' % format)

    def show(self, page_id, id, format='html'):
        c.page = model.Page.getByTitle(page_id)
        id = int(id)
        other_id = int(request.params.get('diffversion', -1))
        if other_id < 0:
            other_id = id - 1
        c.page_rev = c.page.getRevision(id)
        c.other_rev = c.page.getRevision(other_id)
        if c.page is None or c.page_rev is None:
            abort(404)

        if c.other_rev:
            differ = difflib.Differ()
            c.diff = differ.compare(c.other_rev.body.splitlines(), 
                                    c.page_rev.body.splitlines())

        return render('/history/view.%s' % format)


class HistoryPlugin(Plugin):

    def __init__(self, **options):
        config['mtp.page_actions'][('pages', 'show')].append(self.pageActions)
        config['mtp.page_actions'][('revisions', 'show')].append(self.showHistoryActions)
        config['mtp.page_actions'][('revisions', 'index')].append(self.historyActions)
        config['mtp.extra_css'].append('/history/history.css')
        
        config['mtp.controllers']['revisions'] = HistoryController
        config['mtp.map'].pageResource('revision', 'revisions')

    def pageActions(self):
        return (
            PageAction("History", 
                h.url_for('page_revisions', page_id=c.page.urlTitle())),
        )

    def historyActions(self):
        return [
            PageAction("Show Original", 
                h.url_for('page', id=c.page.urlTitle())),
        ]

    def showHistoryActions(self):
        return self.historyActions() + [
            PageAction("History List", 
                h.url_for('page_revisions', page_id=c.page.urlTitle()))
        ]

